<template>
  <div style="max-width: 400px; margin: 50px auto;">
    <h2 style="text-align: center; margin-bottom: 30px;">用户注册</h2>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请设置用户名' }]">
        <el-input v-model="form.username" placeholder="请设置用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password" :rules="[{ required: true, message: '请设置密码' }]">
        <el-input v-model="form.password" type="password" placeholder="请设置密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%;" @click="handleRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useStore } from '../store'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const form = ref({
  username: '',
  password: ''
})
const store = useStore()
const router = useRouter()

// 注册逻辑
const handleRegister = async () => {
  if (!form.value.username || !form.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }
  const success = await store.register(form.value.username, form.value.password)
  if (success) {
    ElMessage.success('注册成功，即将跳转到登录页')
    setTimeout(() => {
      router.push('/login')
    }, 1000)
  } else {
    ElMessage.error('用户名已存在')
  }
}
</script>
